package com.laikan.reader.bookreader.activity;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.*;
import android.widget.AdapterView.OnItemClickListener;
import com.laikan.library.components.activitys.BasicActivity;
import com.laikan.library.managers.ToastMgr;
import com.laikan.library.utils.SPUtil;
import com.laikan.reader.R;
import com.laikan.reader.apirequester.ChapterAutoBuy;
import com.laikan.reader.core.bean.SettingMore;
import com.laikan.reader.core.utils.ActivityUitl;
import com.laikan.reader.core.utils.PublicUtil;
import com.laikan.reader.core.utils.SystemUtil;
import com.laikan.reader.core.warm.WarmWindow;
import com.laikan.reader.database.db.*;
import com.laikan.reader.database.db.NetBroadcastReceiver.netEventHandler;
import com.lidroid.xutils.exception.DbException;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @author wx
 * @version 创建时间：2015-12-29 下午1:50:42 type 类型 1是翻页设置 没有距上距离的标题 2 是内容 可以点击
 *          3是没有边距的标题
 * @E-mail wx1343571153@163.com
 */

public class ReaderSettingMore extends BasicActivity implements netEventHandler {

    private static final String ACTION = "com.laikan.download.progress";
    String url1 = "http://down.motieimg.com/down/FZXKT_GB18030.ttf",// 新楷体
        url2 = "http://down.motieimg.com/down/FZLTHJW.ttf",// 兰亭黑
        url3 = "http://down.motieimg.com/down/FZXY_GBK.ttf";// 细园
    DownloadManager downloadManager;
    String target1, target2, target3;
    private List<SettingMore> list = new ArrayList<SettingMore>();
    private ListView listview;
    private SettingAdapter settingAdapter;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            super.handleMessage(msg);
            settingAdapter.updataView(msg.what, listview, msg.obj + "%");

        }
    };
    private MyBroadcast broadcast;
    private IntentFilter filter;
    private int anim;
    private Bitmap redGouDrawable;
    private String fontTypePath = "/LaikanReader/font/";
    private int typeface_check_dex;
    private RelativeLayout back_layout;
    private ImageView back_tv;
    Drawable drawable_back_tv;
    private ImageView notice_switcher_img;
    private WarmWindow warmWindow;
    private String bookId;
    private ChapterAutoBuy chapterAutoBuy;
    private LinearLayout lin_autoBuy;
    private boolean autoBuySetting;

    @Override
    public void onNetChange() {

        try {
            if (NetUtil.getNetworkState(this) == NetUtil.NETWORN_NONE) {
                ToastMgr.showShortToast("当前网络不可以使用");
                System.out.println("网络不可以使用");
            }else if (NetUtil.getNetworkState(this) == NetUtil.NETWORN_WIFI) {
                System.out.println("网络WIFI");
                if (downloadManager != null) {
                    if (!downloadManager.IsInsert("1")) {
                        if (downloadManager.getDownloadInfo("1").isDownload()) {
                            downloadManager.resumeDownload(downloadManager.getDownloadInfo(0), new DownloadRequestCallBack(downloadManager.getDownloadInfo("1")));
                        }
                    }

                    if (!downloadManager.IsInsert("2")) {
                        if (downloadManager.getDownloadInfo("2").isDownload()) {
                            downloadManager.resumeDownload(downloadManager.getDownloadInfo(1), new DownloadRequestCallBack(downloadManager.getDownloadInfo("2")));
                        }
                    }

                    if (!downloadManager.IsInsert("3")) {
                        if (downloadManager.getDownloadInfo("3").isDownload()) {
                            downloadManager.resumeDownload(downloadManager.getDownloadInfo(2), new DownloadRequestCallBack(downloadManager.getDownloadInfo("3")));
                        }
                    }

                }

            }else if (NetUtil.getNetworkState(this) == NetUtil.NETWORN_MOBILE) {
                ToastMgr.showShortToast("当前手机网络，已停止下载");
                System.out.println("手机网络");
                downloadManager.stopAllDownload();
            }
        }catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    @Override
    protected void assignViews() {
        setContentView(R.layout.read_setting_more);
        NetBroadcastReceiver.mListeners.add(this);
        broadcast = new MyBroadcast();
        filter = new IntentFilter(ACTION);
        lin_autoBuy = (LinearLayout)findViewById(R.id.lin_autoBuy);
        notice_switcher_img = (ImageView)findViewById(R.id.notice_switcher_img);
        back_layout = (RelativeLayout)findViewById(R.id.back_layout);
        back_tv = (ImageView)findViewById(R.id.iv_back);
        listview = (ListView)findViewById(R.id.listview);
    }

    /*
     * (non-Javadoc)
     *
     * @see android.support.v4.app.FragmentActivity#onResume()
     */
    @Override
    protected void onResume() {

        registerReceiver(broadcast, filter);
        super.onResume();

    }

    /*
     * @Override public void onDestroy() { try { if (settingAdapter != null &&
     * downloadManager != null) { downloadManager.backupDownloadInfoList(); } }
     * catch (DbException e) { KLog.e(e.getMessage(), e); }
     * super.onDestroy(); }
     */
    @SuppressLint ("SdCardPath")
    @Override
    protected void initData() {
        warmWindow = new WarmWindow();
        chapterAutoBuy = new ChapterAutoBuy(mContext);
        chapterAutoBuy.setRefreOnClient(new ChapterAutoBuy.RefreshWindowOnClient() {
            @Override
            public void refreWindow(boolean autoBuy,int responseType) {
                autoBuySetting = autoBuy;
                if(responseType == 1){
                    lin_autoBuy.setVisibility(View.VISIBLE);
                }
                int resId = autoBuy ? R.drawable.lk_setting_kai : R.drawable.lk_setting_guan;
                notice_switcher_img.setImageResource(resId);
            }


        });
        bookId = getIntent().getStringExtra("bookId");
        if(SystemUtil.isLogin()){
            chapterAutoBuy.getAutoStatus(SPUtil.getString("token", ""), bookId);
        }
        drawable_back_tv = new BitmapDrawable(PublicUtil.getAlphaBitmap(PublicUtil.readBitMap(mContext,R.drawable.lk_back_small),Color.parseColor("#66ccdd")));
        back_tv.setImageDrawable(drawable_back_tv);
        File filePath = PublicUtil.getRootPath();
        redGouDrawable = PublicUtil.getAlphaBitmap(PublicUtil.readBitMap(mContext, R.drawable.whitegou), Color.parseColor("#66ccdd"));
        downloadManager = DownloadService.getDownloadManager(getApplicationContext());
        target1 = filePath.getPath() + fontTypePath + "FZXKT.ttf";
        target2 = filePath.getPath() + fontTypePath + "FZLTHJW.ttf";
        target3 = filePath.getPath() + fontTypePath + "FZXY.ttf";
        anim = getIntent().getIntExtra("anim", 2);
        typeface_check_dex = getIntent().getIntExtra("typeface_check_dex", 1);
        SettingMore more = new SettingMore();
        more.setContext("阅读字体:");
        more.setType(3);
        list.add(more);
        more = new SettingMore();
        more.setContext("系统默认");
        more.setGroup(2);
        more.setType(2);
        list.add(more);
        more = new SettingMore();
        more.setContext("方正新楷体");
        more.setFontM("(24.18M)");
        more.setDownLoad(true);
        more.setGroup(2);
        more.setType(2);
        more.setDownSub(0);
        list.add(more);
        more = new SettingMore();
        more.setContext("方正兰亭黑简体");
        more.setFontM("(2.4M)");
        more.setGroup(2);
        more.setDownLoad(true);
        more.setType(2);
        more.setDownSub(1);
        list.add(more);
        more = new SettingMore();
        more.setContext("方正细圆");
        more.setFontM("(9.87M)");
        more.setGroup(2);
        more.setDownLoad(true);
        more.setType(2);
        more.setDownSub(2);
        more.setEnd(true);
        list.add(more);
        list.get(SPUtil.getInt("typeface_check", 1)).setShow(true);
        settingAdapter = new SettingAdapter(getApplicationContext());
        listview.setAdapter(settingAdapter);

    }

    /*
     * (non-Javadoc)
     *
     * @see com.laikan.reader.BasicActivity#setListener()
     */
    @Override
    protected void setListener() {
        notice_switcher_img.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if (SystemUtil.isLogin()) {
                    String  sendAutoBuy = autoBuySetting ? "false" : "true";
                    chapterAutoBuy.setAutoStatus(SPUtil.getString("token", ""), bookId, sendAutoBuy);

                }else {
                    warmWindow.showPickDialog(mContext);
                }
            }
        });
        back_layout.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        listview.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if(list.get(position).isShow()){
                    return;
                }
                DownloadInfo downloadInfo = null;
                if (list.get(position).getType() == 2) {
                    if (position == 2) {
                        if (!downloadManager.IsInsert("1")) {
                            downloadInfo = downloadManager.getDownloadInfo("1");
                            if (!downloadInfo.isSuccess()) {
                                return;
                            }
                        }else {
                            return;
                        }

                        SPUtil.putInt("typeface_check", 2);
                    }else if (position == 3) {
                        if (!downloadManager.IsInsert("2")) {
                            downloadInfo = downloadManager.getDownloadInfo("2");
                            if (!downloadInfo.isSuccess()) {
                                return;
                            }
                        }else {
                            return;
                        }
                        SPUtil.putInt("typeface_check", 3);
                    }else if (position == 4) {
                        if (!downloadManager.IsInsert("3")) {
                            downloadInfo = downloadManager.getDownloadInfo("3");
                            if (!downloadInfo.isSuccess()) {
                                return;
                            }
                        }else {
                            return;
                        }
                        SPUtil.putInt("typeface_check", 4);
                    }
                    if (position == 1) {
                        SPUtil.putInt("typeface_check", 1);
                    }
                    for (int i = 0; i < list.size(); i++) {
                        if (list.get(position).getGroup() == list.get(i).getGroup()) {
                            list.get(i).setShow(false);
                        }
                    }

                    list.get(position).setShow(true);
//                    View childView = listview.getChildAt(position);
//                    listview.getAdapter().getView(position,childView,listview);
                    settingAdapter.notifyDataSetChanged();
                }
            }
        });
    }


    /*
     * (non-Javadoc)
     *
     * @see android.support.v4.app.FragmentActivity#onDestroy()
     */
    @Override
    protected void onDestroy() {

        unregisterReceiver(broadcast);
        if (typeface_check_dex != SPUtil.getInt("typeface_check", 1)) {
            Intent intent = new Intent();
            //把返回数据存入Intent
            intent.putExtra("result", "My name is linjiqin");
            //设置返回数据
            this.setResult(1, intent);
        }
        super.onDestroy();
    }

    class SettingAdapter extends BaseAdapter {

        private final Context mContext;
        private final LayoutInflater mInflater;
        DownloadInfo downloadInfo;

        public SettingAdapter(Context context) {
            this.mContext = context;
            mInflater = LayoutInflater.from(mContext);
        }

        @Override
        public int getCount() {

            return list.size();
        }

        @Override
        public Object getItem(int position) {

            return null;
        }

        @Override
        public long getItemId(int position) {

            return 0;
        }

        public void updataView(int posi, ListView listView, String msg) {
            int visibleFirstPosi = listView.getFirstVisiblePosition();
            int visibleLastPosi = listView.getLastVisiblePosition();
            if (posi >= visibleFirstPosi && posi <= visibleLastPosi) {
                View view = listView.getChildAt(posi);
                TextView down = (TextView)view.findViewById(R.id.down);
                TextView fontM = (TextView)view.findViewById(R.id.fontM);
                down.setText(msg);
                fontM.setText(list.get(posi).getFontM());
            }
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {

            downloadInfo = null;
            View view1_1 = mInflater.inflate(R.layout.setting_more_itme1_1, null);
            View view1 = mInflater.inflate(R.layout.setting_more_itme1, null);
            View view2 = mInflater.inflate(R.layout.setting_more_itme2, null);
            TextView text1_1 = (TextView)view1_1.findViewById(R.id.item1_1_text);
            TextView text1 = (TextView)view1.findViewById(R.id.item1_text);
            TextView text2 = (TextView)view2.findViewById(R.id.item_2_text);
            ImageView item_2_image = (ImageView)view2.findViewById(R.id.item_2_image);
            final TextView down = (TextView)view2.findViewById(R.id.down);
            View line = view2.findViewById(R.id.line);
            TextView fontM = (TextView)view2.findViewById(R.id.fontM);
            down.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (!ActivityUitl.isNetworkAvailable(mContext)) {
                        ToastMgr.showShortToast(R.string.laikan_network_anomaly);
                        return;
                    }
                    try {
                        if (position == 2) {

                            downloadManager.addNewDownload(1, "1", url1, "", target1, true, true, null);
                            downloadInfo = downloadManager.getDownloadInfo("1");

                        }else if (position == 3) {

                            downloadManager.addNewDownload(2, "2", url2, "", target2, true, true, null);

                            downloadInfo = downloadManager.getDownloadInfo("2");
                        }else if (position == 4) {

                            downloadManager.addNewDownload(3, "3", url3, "", target3, true, true, null);
                            downloadInfo = downloadManager.getDownloadInfo("3");

                        }else if(position == 1){
                            return;
                        }
                        downloadInfo.setDownload(true);
                        down.setClickable(false);
                    }catch (DbException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            });
            if (list.get(position).getType() == 3) {
                text1.setText(list.get(position).getContext());
                convertView = view1;
            }else if (list.get(position).getType() == 2) {
                text2.setText(list.get(position).getContext());
                if (list.get(position).isShow()) {
                    item_2_image.setImageBitmap(redGouDrawable);
                    item_2_image.setVisibility(View.VISIBLE);
                }else {
                    item_2_image.setVisibility(View.GONE);
                }
                if (list.get(position).isEnd()) {
//                    line.setVisibility(View.GONE);
                }
                convertView = view2;
            }

            if (position == 2) {
                if (!downloadManager.IsInsert("1")) {
                    downloadInfo = downloadManager.getDownloadInfo("1");
                }

            }else if (position == 3) {
                if (!downloadManager.IsInsert("2")) {
                    downloadInfo = downloadManager.getDownloadInfo("2");
                }
            }else if (position == 4) {
                if (!downloadManager.IsInsert("3")) {
                    downloadInfo = downloadManager.getDownloadInfo("3");
                }
            }
            if (position >= 2) {
                if (downloadInfo != null) {
                    if (downloadInfo.isDownload()) {
                        if (downloadInfo.isSuccess()) {
                            down.setVisibility(View.GONE);
                            fontM.setVisibility(View.GONE);
                        }else {
                            down.setText(downloadInfo.getProgressText());
                            fontM.setText(list.get(position).getFontM());
                        }
                    }

                    if (downloadInfo.isSuccess()) {
                        down.setVisibility(View.GONE);
                        fontM.setVisibility(View.GONE);
                    }
                    if (downloadInfo.isIsfail()) {
                        down.setText("下载");
                        fontM.setText(list.get(position).getFontM());
                        try {
                            downloadManager.removeDownload(downloadInfo);
                        }catch (DbException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }

                }else {
                    if (list.get(position).isDownLoad()) {

                        down.setText("下载");
                        fontM.setText(list.get(position).getFontM());
                        down.setVisibility(View.VISIBLE);
                    }else {
                        down.setVisibility(View.GONE);

                    }
                }

            }

            return convertView;
        }

    }

    private class DownloadRequestCallBack extends RequestCallBack<File> {

        int position;
        private DownloadInfo downloadInfo;

        public DownloadRequestCallBack(DownloadInfo downloadInfo) {
            this.downloadInfo = downloadInfo;
            position = (int)downloadInfo.getId();

        }

        @Override
        public void onStart() {
        }

        @Override
        public void onLoading(long total, long current, boolean isUploading) {


            if (position == 1) {
                position = 2;

            }
            if (position == 2) {
                position = 3;
            }
            if (position == 3) {
                position = 4;
            }

        }

        @Override
        public void onSuccess(ResponseInfo<File> responseInfo) {
            downloadInfo.setSuccess(true);
            System.out.println("下载完成");
        }

        @Override
        public void onFailure(HttpException error, String msg) {
        }

        @Override
        public void onCancelled() {
        }
    }

	/*
     * (non-Javadoc)
	 * 
	 * @see
	 * com.laikan.reader.database.db.NetBroadcastReceiver.netEventHandler#onNetChange
	 * ()
	 */

    class MyBroadcast extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            int position = Integer.parseInt(intent.getStringExtra("position"));
            String values = intent.getStringExtra("values");
            settingAdapter.updataView(position, listview, values);

        }
    }
}
